﻿using OpenNETCF.IoC;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace IoTCM
{
    internal partial class RequestProcessor
    {
        private void ProcessPost(HttpListenerContext context)
        {
            Debug.WriteLine("POST: " + context.Request.Url.ToString());

            var host = GetRequestedHost(context);
            if (host == null) return;

            switch (context.Request.Url.Segments.Length)
            {
                case 2:
                    switch (context.Request.Url.Segments[1].ToLower().Replace("/", string.Empty))
                    {
                        case "session":
                            // get the username
                            var user = (GetRequestParameter(context, "user") ?? string.Empty).ToLower();

                            // get the password

                            // ******************** WARNING ******************** 
                            // This is plain text! Do not deploy this in a production app!
                            // ******************** WARNING ******************** 
                            var password = (GetRequestParameter(context, "password") ?? string.Empty).ToLower();

                            // attempt to create a session
                            var session = m_sessionService.StartSession(user, password);

                            // if the return is null, the user is invalid
                            if (session == null)
                            {
                                SendInvalidCredentialsError(context, host);
                                return;
                            }

                            // send back the session token
                            var sessionResult = host.GetSerializedNameValuePair("session", session.Token);
                            SendResponse(context, sessionResult, host.MimeType);

                            break;
                    }

                    break;
                default:
                    break;
            }
        }
    }
}
